using System;
using System.Collections;

namespace Sedna.Core.Controller.Common
{
	public class CommandArgumentParamBuilder
	{
		private CommandArgumentParamBuilder()
		{
		}

		public static IList BuildParams(IDictionary executionContext, string prefix)
		{
			IList result = new ArrayList();

			if(executionContext == null)
			{
				return result;
			}

			string argsStr = (string)executionContext["infrastructure.commandArgument"];
			if(argsStr == null || argsStr.Equals(string.Empty))
			{
				return result;
			}

			IDictionary args = ParseArguments(argsStr);

			prefix = prefix!=null?prefix:"cmd_";

			for(IDictionaryEnumerator en = args.GetEnumerator(); en.MoveNext();)
			{
				result.Add(new NameValueActionParam(prefix + (string)en.Key, (string)en.Value));
			}

			return result;

		}

		private static IDictionary ParseArguments(string argsStr)
		{
			string[] args =  argsStr.Split(';');
			IDictionary name2value = new Hashtable();
			if(args == null || args.Length == 0)
			{
				return name2value;
			}
			foreach(string arg in args)
			{
				string[] nv = arg.Split('=');
				if(nv != null && nv.Length == 2)
				{
					name2value.Add(nv[0], nv[1]);
				}
			}

			return name2value;
		}

	}
}
